package com.moresir.validatetools.rules.list.other;

import com.moresir.validatetools.common.response.ResponseEnum;
import com.moresir.validatetools.exceptions.BusinessException;
import com.moresir.validatetools.impl.Form;
import com.moresir.validatetools.rules.list.AbstractRule;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

public class RuleDateFormat extends AbstractRule {
    @Override
    public boolean isOkay(Form f) {
        Optional<String> s = f.getString(rule.getField());
        String formatString = rule.getParams().get(0);

        try{
            if(! s.isPresent()){
                return false;
            }

            //字符串转时间
            SimpleDateFormat sdf = new SimpleDateFormat(formatString);
            Date date = sdf.parse(s.get());

            //时间转字符串
            String dateStr = sdf.format(date);
            return s.filter(str -> str.equals(dateStr)).isPresent();

        } catch (ParseException e){
            throw new BusinessException(ResponseEnum.VALIDATE_EXCEPTION.getCode(), "时间格式校验异常" + e.getMessage());
        }
    }
}
